package com.xx.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {

    public Object createProxy(Object target) {
        // 创建一个动态类对象
        Enhancer enhancer = new Enhancer();

        // 确定需要增强的类，设置其父类
        enhancer.setSuperclass(target.getClass());

        // 添加回调函数
        enhancer.setCallback(this);

        // 返回创建的代理类
        return enhancer.create();
    }

    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        log(method.getName());

        return methodProxy.invokeSuper(proxy, args);
    }

    public void log(String method) {
        System.out.println("执行了" + method + "方法");
    }
}
